#!/bin/bash
# 创建同步用户脚本

#1 获取输入参数个数，如果没有参数，直接退出
FILE_COUNT=$#
if((FILE_COUNT!=2)); then
    echo ">>> 错误：未传递文件参数！"
    echo "  用法：show_master_status.sh 参数一：MASTER_IP 参数二：MYSQL_ROOT_PASSWORD"
    exit;
fi
MASTER_IP=$1
MYSQL_ROOT_PASSWORD=$2
REPLIC=replic

# 主库创建同步用户
SQL_HAS_REPLIC=`docker exec -t mysql5719_slave mysql -h$MASTER_IP -uroot -p$2 -Bse "use mysql;SELECT Host,User FROM user WHERE User='replic';"| grep replic | wc -l`
if (( $SQL_HAS_REPLIC == 0 )); then
    echo "未创建主从同步用户replic，开始创建..."
    docker exec -t mysql5719_slave mysql -h$MASTER_IP -uroot -p$2 -Bse "create user 'replic'@'%' identified by 'replic';grant replication slave on *.* to 'replic'@'%';flush privileges;"
fi


# exit
# 获取master的binlog信息（log_file），日志偏移量（log_pos）
BINlOG=`docker exec -t mysql5719_slave mysql -h $MASTER_IP -uroot -p$MYSQL_ROOT_PASSWORD -Bse "show master status;"| grep mysql-bin `
# 拼写从机连接sql
# 参考：change master to master_host='192.168.56.102',master_user='replic',master_password='replic',master_log_file='mysql-bin.000003',master_log_pos=154;
SQL_SLAVE_OF=`echo $BINlOG | awk '{print "change master to master_host='\'$MASTER_IP\'',master_user='\'$REPLIC\'',master_password='\'$REPLIC\'',master_log_file='\''"$1"'\'',master_log_pos="$2";"}'`
echo $SQL_SLAVE_OF 

# 从机执行同步

docker exec -t mysql5719_slave mysql -uroot -p$MYSQL_ROOT_PASSWORD -Bse "$SQL_SLAVE_OF;start slave;"
docker exec -t mysql5719_slave mysql -uroot -p$MYSQL_ROOT_PASSWORD -Bse "show slave status\G;" | grep Running

echo "如果出现2个yes表示主从搭建成功！"





